package com.solidsnake.scala.service

import com.solidsnake.scala.http.{HttpHandlerField, HttpUtils}
import java.nio.charset.Charset
import java.net.URLEncoder

/**
 * Created with IntelliJ IDEA.
 * User: Solidsnake
 * Date: 13-11-24
 * Time: 下午4:50
 * To change this template use File | Settings | File Templates.
 */
object QueryService {
  def getQueryPage(clientParams : ClientParams, url : String) = {
    val requestHandler = Map(HttpHandlerField.COOKIE -> clientParams.cookie)
    HttpUtils.getText(url, Map(), Charset.forName("UTF-8"), requestHandler, true)
  }

  /**
   * 获得查询类型 法人，非法人，其他市场主体
   */
  def changeQueryType(clientParams : ClientParams, url : String, typeT : String) = {
    val requestHandler = Map(HttpHandlerField.COOKIE -> clientParams.cookie,
    HttpHandlerField.REFERER -> "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx",
      "X-MicrosoftAjax"->"Delta=true")
    val requestParams =
      Map("__EVENTARGUMENT" -> "",
        "__LASTFOCUS" -> "",
        "NameCenter" -> "on",
        "SSDJNCREnterPage1$rblHadTradeNameProof" -> "0",
        "SSDJNCREnterPage1$txtTradeName" -> "",
        "SSDJNCREnterPage1$txtCheckCode" -> "",
        "SSDJNCSLHAEnterPage1$txtEntRegNO" -> "",
        "SSDJNCSLHAEnterPage1$txtEntName" -> "",
        "SSDJNCAEnterPage1$txtNameRegNO" -> "",
        "SSDJNCAEnterPage1$txtEntName" -> "",
        "SSDJNCCEnterPage1$txtNameRegNO" -> "",
        "SSDJNCCEnterPage1$txtEntName" -> "",
        "__VIEWSTATE" -> clientParams.encodeViewState) ++
        getQueryTypeParams(typeT)
    HttpUtils.postText(url, requestParams, Charset.forName("UTF-8"), requestHandler, true)
  }

  def getQueryTypeParams(typeT : String) : Map[String, String] = {
    typeT match {
      case "1" =>
        Map("smObj"->"SSDJNCREnterPage1$upBigEntType|SSDJNCREnterPage1$rblBigEntType$0",
            "__EVENTTARGET" -> "SSDJNCREnterPage1$rblBigEntType$0",
            "SSDJNCREnterPage1$rblBigEntType"->"0")
      case "2" =>
        Map("smObj"->"SSDJNCREnterPage1$upBigEntType|SSDJNCREnterPage1$rblBigEntType$1",
          "__EVENTTARGET" -> "SSDJNCREnterPage1$rblBigEntType$1",
          "SSDJNCREnterPage1$rblBigEntType"->"1")
      case "3" =>
        Map("smObj"->"SSDJNCREnterPage1$upBigEntType|SSDJNCREnterPage1$rblBigEntType$2",
          "__EVENTTARGET" -> "SSDJNCREnterPage1$rblBigEntType$2",
          "SSDJNCREnterPage1$rblBigEntType"->"4")
    }
  }

  def getQueryTypeViewState(text : String) = {
    val resultParamArray = text.split('|')
    resultParamArray(resultParamArray.indexOf("__VIEWSTATE") + 1)
  }


  def queryContent(url : String, clientParams : ClientParams)(queryField : String, vc : String ,typeT : String) = {
    val params =  Map(
      "__EVENTTARGET" -> "",
      "__EVENTARGUMENT" -> "",
      "__LASTFOCUS" -> "",
      "__VIEWSTATE" -> clientParams.encodeViewState,
      "NameCenter" -> "no",
      "SSDJNCREnterPage1$rblHadTradeNameProof" -> "0",
      "SSDJNCREnterPage1$rblBigEntType" -> typeT,
      "SSDJNCREnterPage1$txtTradeName" -> queryField,
      "SSDJNCREnterPage1$txtCheckCode" -> vc,
      "SSDJNCSLHAEnterPage1$txtEntRegNO" -> "",
      "SSDJNCSLHAEnterPage1$txtEntName" -> "",
      "SSDJNCAEnterPage1$txtNameRegNO" -> "",
      "SSDJNCAEnterPage1$txtEntName" -> "",
      "SSDJNCCEnterPage1$txtNameRegNO" -> "",
      "SSDJNCCEnterPage1$txtEntName" -> "",
      "SSDJNCREnterPage1$btnOnlyTradeName" -> "字号查重",
      "smObj" -> "SSDJNCREnterPage1$upTopBtn|SSDJNCREnterPage1$btnOnlyTradeName"
    )
    val header = Map(HttpHandlerField.REFERER -> "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx",
      HttpHandlerField.COOKIE -> clientParams.cookie)
    val result = HttpUtils.postText(
      url,
      params, Charset.forName("UTF-8"), header, true)
    //println(result._3)
    result
  }


  def getContextType(context : String) : Int= {
    if(context.contains("字号已被其他企业使用")) {
      0
    }else if(context.contains("字号未被其他企业使用，是否可用，最终由登记机关核定。")) {
      1
    }else if(context.contains("字号中不得含有行业用语!")) {
      2
    }else if(context.contains("验证码错误")) {
      -1
    }else {
      3 // 字号只能为中文
    }
  }




  def main(str : Array[String]) = {
    var index = 0

    var count = 0
    var flag = false
    var cookie: ClientParams = null
    while (!flag) {
      count += 1
      println(count)
      try {
        cookie = LoginService.login("zhangxin163", "8624608")
        flag = if (cookie == null) false else true
      } catch {
        case e: Exception => println(e); new RuntimeException(e)
      }
    }

    println("登录成功\n\n\n")
    var contextType = -99
    var content: (Map[String, String], Map[String, String], String) = null
    while (contextType < 0) {
      try {
        val queryPage = this.getQueryPage(cookie, "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx")
        cookie.loadCookie(queryPage._1, queryPage._2)
        cookie.loadViewState(queryPage._3)

        val validateUrl = ValidateCodeService.getQueryValidateUrl(queryPage._3)
        val queryValidateResult = ValidateCodeService.requestQueryValidateCode(validateUrl, cookie.cookie)
        cookie.loadCookie(queryValidateResult._1, queryValidateResult._2)
        val vc = ValidateCodeService.calculateValidateCodeDate(queryValidateResult._3)

        val changeQueryType = this.changeQueryType(cookie, "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx", "1")
        cookie.loadCookie(changeQueryType._1, changeQueryType._2)
        cookie.viewState = this.getQueryTypeViewState(changeQueryType._3)
        content = this.queryContent("http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx", cookie)("福建", vc, "1")

        contextType = getContextType(content._3)
      } catch {
        case e: Exception => println(e); new RuntimeException(e)
      }
    }


    contextType match {
      case 1 => println("字号未被其他企业使用")
      case 2 => println("字号中不得含有行业用语!")
      case 3 => println("字号填写只能为中文")
      case 0 =>
        val s  = CompanyInfo.regexCompanyGroup(content _3)
        println(s.size)
    }

  }


}
